package com.ratingbay.lucene;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.FSDirectory;

import com.ratingbay.console.common.RatingBayConst;
import com.ratingbay.console.model.TwitterUser;

public class Test {

	public  static void query(int pageNo,int pageSize) throws IOException{
		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(RatingBayConst.LUCENE_FILE_PATH)));
		 IndexSearcher searcher = new IndexSearcher(reader);
		    WildcardQuery q=new WildcardQuery(new Term("username","*a*"));
		    Sort sort = new Sort();  
	        SortField sf = new SortField("tweetsCount", SortField.Type.INT,true);  
	        sort.setSort(sf); 
		    TopDocs result=searcher.search(q, pageSize);
		    int index=(pageNo-1)*pageSize;
		    ScoreDoc scoreDoc=null;
	        //若是当前页是第一页面scoreDoc=null 1729060644
	        if(index>0){
	            //因为索引是从0开端所以要index-1
	            scoreDoc=result.scoreDocs[index-1];
	        }
	        TopDocs hits= searcher.searchAfter(scoreDoc,q,pageSize);
	        for(ScoreDoc sd:hits.scoreDocs){
	        	Document doc=searcher.doc(sd.doc);
	        	System.out.println(doc.get("id"));
	        }
	}
	public  static void query(String s) throws IOException{
		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(RatingBayConst.LUCENE_FILE_PATH)));
		 IndexSearcher searcher = new IndexSearcher(reader);
		    WildcardQuery q=new WildcardQuery(new Term("username","*"+s+"*"));
		    TopDocs result=searcher.search(q, 100);
		    System.out.println(result.totalHits);
		   
	}
	
	public static void main(String[] args) throws IOException {
		long s=System.currentTimeMillis();
		List<Long> l=LuceneQuery.search("username", "a",0,1,null,null);
		System.out.println(l.get(0));
		//query("a");
		long e=System.currentTimeMillis();
		System.out.println((e-s)+"ms");
		
	}
}
